package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

/**
 * @Author fengye
 * @Date 2023/4/8 10:07
 **/
public class MergeTwoLists21 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        ListNode head = null;
        if(list1.val > list2.val) {
            head = list2;
            list2 = list2.next;
        } else {
            head = list1;
            list1 = list1.next;
        }
        ListNode pos = head;
        while (list1!=null || list2!=null) {
            if(list1 == null) {
                pos.next = list2;
                break;
            }
            if(list2 == null) {
                pos.next = list1;
                break;
            }
            if(list1.val > list2.val) {
                pos.next = list2;
                list2 = list2.next;
            } else {
                pos.next = list1;
                list1 = list1.next;
            }
            pos = pos.next;
        }

        return head;
    }
}
